using Microsoft.EntityFrameworkCore;
using UniversalAdminSystem.Domian.Core.ValueObjects;
using UniversalAdminSystem.Domian.PermissionManagement.Aggregate;
using UniversalAdminSystem.Domian.PermissionManagement.IRepository;
using UniversalAdminSystem.Infrastructure.Persistence.DbContexts;

namespace UniversalAdminSystem.Infrastructure.Persistence.Repositories;

public class RoleRepository : BaseRepository<Role>, IRoleRepository
{
    public RoleRepository(UniversalAdminSystemDbContext dbContext) : base(dbContext)
    {
    }

    public override async Task<Role?> GetByGuidAsync(Guid guid)
    {
        var roleId = RoleId.Create(guid);
        var role = await _TDs
            .Include(r => r.Permissions)  // 包含权限关联
            .FirstOrDefaultAsync(r => r.RoleId == roleId);
        return role;
    }
    public async Task<bool> ExistsAsync(string name)
    {
        if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));
        return await _TDs.AnyAsync(r => r.Name == name);
    }

    public async Task<IEnumerable<Role>> GetByIdsAsync(IEnumerable<Guid> ids)
    {
        if (ids == null) throw new ArgumentNullException(nameof(ids));
        return await _TDs
            .Include(r => r.Permissions)
            .Where(r => ids.Contains(r.RoleId))
            .ToListAsync();
    }

    public async Task<Role?> GetByNameAsync(string name)
    {
        if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));
        
        // 使用更明确的比较方式
        var allRoles = await _TDs
            .Include(r => r.Permissions)
            .ToListAsync();
            
        return allRoles.FirstOrDefault(r => r.Name.Value == name);
    }

    public async Task<IReadOnlyCollection<Guid>> GetPermissionIdsAsync(Guid roleId)
    {
        var role = await _TDs
            .Include(r => r.Permissions)
            .FirstOrDefaultAsync(r => r.RoleId == roleId);
        if (role == null) throw new KeyNotFoundException("角色不存在");
        return role.PermissionIds.ToList().AsReadOnly();
    }

    /// <summary>
    /// 获取角色及其权限（包含权限导航属性）
    /// </summary>
    public async Task<Role?> GetRoleWithPermissionsAsync(Guid roleId)
    {
        return await _TDs
            .Include(r => r.Permissions)
            .FirstOrDefaultAsync(r => r.RoleId == roleId);
    }

    /// <summary>
    /// 获取所有角色及其权限
    /// </summary>
    public async Task<IEnumerable<Role>> GetAllRolesWithPermissionsAsync()
    {
        return await _TDs
            .Include(r => r.Permissions)
            .ToListAsync();
    }
}